//
//  WKWeb3Helper.swift
//  WuKongUsernameLogin
//
//  Created by tt on 2023/9/7.
//

import Foundation
import Web3swift


@objc public class WKWeb3Helper:NSObject {
    // 生成助记词
    @objc public static func generateMnemonics() ->String{
       let mm = try? BIP39.generateMnemonics(bitsOfEntropy: 128)
       return mm!.lowercased()
        
    }
    
    @objc public static func generatePrivatekey(_ mnemonics:String) ->String? {
        
        let tempWalletAddress = try? BIP32Keystore(mnemonics: mnemonics,password: "")
        if tempWalletAddress?.addresses?.count ?? 0 > 0 {
            let privateData = try! tempWalletAddress!.UNSAFE_getPrivateKeyData(password: "", account: tempWalletAddress!.addresses![0])
            return privateData.toHexString()
        }
        return nil
        
//        guard let seed = BIP39.seedFromMmemonics(mnemonics,password: "") else {
//            return nil
//        }
//        guard let hdNode = HDNode(seed: seed) else {
//            return nil
//        }
//        let publicKeyBytes = hdNode.publicKey.bytes
//        print("publicKeyBytes--->",publicKeyBytes.toHexString())
////       print("zzz---->", Web3.Utils.privateToPublic(hdNode.privateKey!,compressed: true)?.bytes.toHexString())
//        return hdNode.privateKey?.toHexString()
        
//        let tempWalletAddress = try? BIP32Keystore(mnemonics: mnemonics,password: "",prefixPath: "m/44'/60'/0'/0")
        
    }
    
    @objc public static func signPersonalMessage(privateKey:String,data:Data) ->String? {
        guard let privateKeyData = Data.fromHex(privateKey) else {
            return ""
        }
        let web3Rinkeby = Web3.InfuraRinkebyWeb3()
        let keystore = try! EthereumKeystoreV3(privateKey: privateKeyData,password: "")
        let keystoreManager = KeystoreManager([keystore!])
        web3Rinkeby.addKeystoreManager(keystoreManager)
        let address = keystoreManager.addresses![0]
        print("address.address--->",address.address)
        
//        let signMsg = try? web3Rinkeby.wallet.signPersonalMessage(data, account: address,password: "");
    
        let signMsg = try? Web3Signer.signPersonalMessage(data, keystore: keystore!, account: address, password: "",useExtraEntropy: false)
        return signMsg?.toHexString()
    }
    
    @objc public static func privateKeyToPublicKey(_ privateKey:String) -> String? {
        guard let privateKeyData =  Data.fromHex(privateKey) else {
            return ""
        }
       
        return Web3.Utils.privateToPublic(privateKeyData,compressed: true)?.toHexString()
    }
    
    @objc public static func createWallet(mnemonics:String,path:String?) {
        let userDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        var keyPath = path;
        if (keyPath == nil) {
            keyPath = userDir + "/keystore" + "/key.json"
        }

        let tempWalletAddress = try? BIP32Keystore(mnemonics: mnemonics,password: "")
        let keyData = try? JSONEncoder().encode(tempWalletAddress?.keystoreParams)
        FileManager.default.createFile(atPath: keyPath!, contents: keyData, attributes: nil)
    }
    @objc public static func createUserWallet(_ mnemonics:String,uid:String) {
        let userDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let keyDir =  userDir + "/keystore" + "/" + uid;
        let keyPath = keyDir + "/key.json";
        try! FileManager.default.createDirectory(at: URL(fileURLWithPath: keyDir), withIntermediateDirectories: true)
        
        let tempWalletAddress = try? BIP32Keystore(mnemonics: mnemonics,password: "")
        let keyData = try? JSONEncoder().encode(tempWalletAddress?.keystoreParams)
        FileManager.default.createFile(atPath: keyPath, contents: keyData, attributes: nil)
    }
    
    // 是否存在用户钱包
    @objc public static func existUserWallet(_ uid:String) -> Bool{
        let userDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let keyPath = userDir + "/keystore" + "/" + uid + "/key.json";
        return FileManager.default.fileExists(atPath: keyPath)
    }
    
    @objc public static func getUserPrivateKey(_ uid:String) ->String? {
        let userDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let keyDir = userDir + "/keystore" + "/" + uid;
        let web3KeystoreManager = KeystoreManager.managerForPath(keyDir,scanForHDwallets: true);
        if web3KeystoreManager?.addresses?.count ?? 0 > 0 {
            let privateData = try! web3KeystoreManager!.UNSAFE_getPrivateKeyData(password: "", account: web3KeystoreManager!.addresses![0])
            return privateData.toHexString()
        }
        return ""
       
    }
    
    @objc public static func getPrivateKey(keystoreDir:String?) ->String? {
        let userDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        var keyDir = keystoreDir;
        if (keyDir == nil) {
            keyDir = userDir + "/keystore"
        }
        let web3KeystoreManager = KeystoreManager.managerForPath(keyDir!,scanForHDwallets: true);
        if web3KeystoreManager?.addresses?.count ?? 0 > 0 {
    
            let privateData = try! web3KeystoreManager!.UNSAFE_getPrivateKeyData(password: "", account: web3KeystoreManager!.addresses![0])
            return privateData.toHexString()
        }
        return ""
       
    }

    
}
